const router = require('koa-router')();
const { resBody, md5 } = require("../../utils")
const { models, sequelize } = require('../../utils/db');
const { getJwtInfo } = require('../../utils/jwtToken');
const { nanoid } = require('nanoid');
const moment = require('moment');

// 获取列表
router.post('/list', async (ctx, next) => {
    const {
        pn = 1,
        ps = 10,
    } = ctx.request.body;
    const { rows, count } = await models.activation_model.findAndCountAll({
        // raw: true,
        limit: ps,
        offset: (pn - 1) * ps,
        order: [['id', 'DESC']],
        include: [
            {
              model: models.admin_model,
              as: 'createAdmin',
              attributes: ['name']
            }
        ]
    });
    ctx.body = {
        ...resBody.success,
        data: {
            list: rows || [],
            total: count || 0
        }
    };
});

// 生成激活码
router.post('/create', async (ctx, next) => {
    const {
        time,
        timeType,
        count,
        common
    } = ctx.request.body;
    const token = ctx.request.header.authorization;
    const { id: createUser } = getJwtInfo(token);
    if (!time || !timeType || !count) {
        throw (resBody.paramError)
    }
    const timeTypeUnit = {
        1: 'minutes',
        2: 'hours',
        3: 'days',
        4: 'months',
        5: 'years'
    };
    const effecTime = `${time},${timeTypeUnit[timeType]}`;
    const createTime = moment().format();
    const maxId =  await models.activation_model.max('id') || 0;
    const activeCodeArr = [...new Array(count).keys()].map(item => ({
        activeCode: nanoid(10) + (maxId + item + 1),
        effecTime,
        activeState: 1,
        createTime,
        createUser,
        common,
    }));
    await models.activation_model.bulkCreate(activeCodeArr);
    ctx.body = {
        ...resBody.success,
        data: {
            activeCodes: activeCodeArr.map(item => item.activeCode),
        }
    };
});

// 删除激活码
router.post('/delete', async (ctx, next) => {
    const { id } = ctx.request.body;
    if (!id) {
        throw (resBody.paramError)
    }
    await models.activation_model.destroy({
        where: { id }
    });
    ctx.body = resBody.success;
});

module.exports = router